import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async addThumb(params) {
      await api.forumController.addThumb(params);
    },
    async deleteThumb(params) {
      await api.forumController.deleteThumb(params);
    },
    async page(params) {
      const {
        main: {pageNum, conditionValue},
      } = getData();
      let res = await api.forumController.getFindConditional({...params, pageNum, conditionValue});
      const rows = res.data.rows;
      if (res.code == '200') {
        action.commonChange('main.list', res.data.rows);
        let leftData = [],
          rightData = [];
        for (let i = 0; i < rows.length; i++) {
          if (i % 2 == 0) {
            leftData.push(rows[i]);
          } else {
            rightData.push(rows[i]);
          }
        }
        console.log(pageNum);
        console.log(leftData, rightData);
        if (pageNum === 1) {
          action.commonChange('main.leftData', leftData);
          action.commonChange('main.rightData', rightData);
          action.commonChange('main.totalPages', res.data.totalPage);
        } else {
          let newLeftData = leftData.concat(leftData);
          let newRightData = rightData.concat(rightData);
          action.commonChange('main.leftData', newLeftData);
          action.commonChange('main.rightData', newRightData);
          action.commonChange('main.totalPages', res.data.totalPage);
        }
      } else {
        Taro.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000,
        });
      }
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageBPostSearchMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
